package com.huawei.su;

/**
 * https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e?tpId=295&tqId=23256&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj
 */
public class BM18 {
    public static void main(String[] args) {
        int[][] array = {
                {1, 2, 3, 4, 5, 6, 8},
                {2, 3, 4, 5, 6, 7, 9}
        };
        System.out.println(Find(7, array));
    }

    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * @param target int整型
     * @param array  int整型二维数组
     * @return bool布尔型
     */
    public static boolean Find(int target, int[][] array) {
        // write code here
        if (array == null || array.length == 0 || array[0].length == 0 || array[0][0] < target) {
            return false;
        }
        int[] ints = array[0];

        int left = 0;
        int right = ints.length - 1;

        int j;
        while (true) {
            if (left > right) {
                j = right;
                break;
            }
            int middle = (left + right) / 2;
            if (ints[middle] == target) {
                return true;
            } else if (ints[middle] > target) {
                right = middle - 1;
            } else {
                left = middle + 1;
            }
        }
        if (ints[j] > target) {
            j--;
        }
        left = 0;
        right = array.length - 1;

        while (true) {
            if (left > right) {
                break;
            }
            int middle = (left + right) / 2;
            if (array[middle][j] == target) {
                return true;
            } else if (array[middle][j] > target) {
                right = middle - 1;
            } else {
                left = middle + 1;
            }
        }
        return false;
    }
}
